package org.autumn.aqs;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CyclicBarrierTest {
    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(2, () -> {
            System.out.println("finished ....");
        });
        ExecutorService service = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 3; i++) {
            service.submit(() -> {
                System.out.println("task1 begin");
                try {
                    Thread.sleep(1000);
                    cyclicBarrier.await();
                    System.out.println("task1 end");
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }

            });

            service.submit(() -> {
                System.out.println("task2 begin");
                try {
                    Thread.sleep(1000);
                    cyclicBarrier.await();
                    System.out.println("task2 end");
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }

            });
        }

        service.shutdown();
    }
}
